package view;

import controller.WorkerRegistro;
import java.awt.event.KeyEvent;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.table.DefaultTableModel;
import model.Cliente;
import model.ObjetoTablaEnvios;
import util.MaxLengthTextDocument;

public class Registro extends javax.swing.JFrame {

    // ATRIBUTOS
    model.Cliente cliente;  // cliente que ordena el pedido
    Vector columnasTablaEnvios; // vector con los nombres de las columnas de la tabla de envios
    DefaultTableModel modeloTablaEnvios;    //modelo para la tabla de envios
    List<ObjetoTablaEnvios> listaFilasTablaEnvios;  //lista de ObjetoTablaEnvios que contendra el contenido de la tabla de envios
    private int numFilaEditar;  // numero de fila del envio a editar

    // SETTERS Y GETTERS
    public Cliente getCliente() {
        return cliente;
    }

    public void setCliente(Cliente cliente) {
        this.cliente = cliente;
    }

    public Vector getColumnasTablaEnvios() {
        return columnasTablaEnvios;
    }

    public void setColumnasTablaEnvios(Vector columnasTablaEnvios) {
        this.columnasTablaEnvios = columnasTablaEnvios;
    }

    public DefaultTableModel getModeloTablaEnvios() {
        return modeloTablaEnvios;
    }

    public void setModeloTablaEnvios(DefaultTableModel modeloTablaEnvios) {
        this.modeloTablaEnvios = modeloTablaEnvios;
    }

    public List<ObjetoTablaEnvios> getListaFilasTablaEnvios() {
        return listaFilasTablaEnvios;
    }

    public void setListaFilasTablaEnvios(List<ObjetoTablaEnvios> listaFilasTablaEnvios) {
        this.listaFilasTablaEnvios = listaFilasTablaEnvios;
    }

    public int getNumFilaEditar() {
        return numFilaEditar;
    }

    public void setNumFilaEditar(int numFilaEditar) {
        this.numFilaEditar = numFilaEditar;
    }

    public JButton getBtnAceptar() {
        return btnAceptar;
    }

    public void setBtnAceptar(JButton btnAceptar) {
        this.btnAceptar = btnAceptar;
    }

    public JButton getBtnAgregar() {
        return btnAgregar;
    }

    public void setBtnAgregar(JButton btnAgregar) {
        this.btnAgregar = btnAgregar;
    }

    public JButton getBtnBuscar() {
        return btnBuscar;
    }

    public void setBtnBuscar(JButton btnBuscar) {
        this.btnBuscar = btnBuscar;
    }

    public JButton getBtnCancelar() {
        return btnCancelar;
    }

    public void setBtnCancelar(JButton btnCancelar) {
        this.btnCancelar = btnCancelar;
    }

    public JButton getBtnEditar() {
        return btnEditar;
    }

    public void setBtnEditar(JButton btnEditar) {
        this.btnEditar = btnEditar;
    }

    public JButton getBtnEliminar() {
        return btnEliminar;
    }

    public void setBtnEliminar(JButton btnEliminar) {
        this.btnEliminar = btnEliminar;
    }

    public ButtonGroup getButtonGroup1() {
        return buttonGroup1;
    }

    public void setButtonGroup1(ButtonGroup buttonGroup1) {
        this.buttonGroup1 = buttonGroup1;
    }

    public ButtonGroup getButtonGroup2() {
        return buttonGroup2;
    }

    public void setButtonGroup2(ButtonGroup buttonGroup2) {
        this.buttonGroup2 = buttonGroup2;
    }

    public JLabel getjLabel1() {
        return jLabel1;
    }

    public void setjLabel1(JLabel jLabel1) {
        this.jLabel1 = jLabel1;
    }

    public JLabel getjLabel5() {
        return jLabel5;
    }

    public void setjLabel5(JLabel jLabel5) {
        this.jLabel5 = jLabel5;
    }

    public JPanel getjPanel1() {
        return jPanel1;
    }

    public void setjPanel1(JPanel jPanel1) {
        this.jPanel1 = jPanel1;
    }

    public JPanel getjPanel3() {
        return jPanel3;
    }

    public void setjPanel3(JPanel jPanel3) {
        this.jPanel3 = jPanel3;
    }

    public JScrollPane getjScrollPane1() {
        return jScrollPane1;
    }

    public void setjScrollPane1(JScrollPane jScrollPane1) {
        this.jScrollPane1 = jScrollPane1;
    }

    public JLabel getLblApMat() {
        return lblApMat;
    }

    public void setLblApMat(JLabel lblApMat) {
        this.lblApMat = lblApMat;
    }

    public JLabel getLblApPat() {
        return lblApPat;
    }

    public void setLblApPat(JLabel lblApPat) {
        this.lblApPat = lblApPat;
    }

    public JLabel getLblDni() {
        return lblDni;
    }

    public void setLblDni(JLabel lblDni) {
        this.lblDni = lblDni;
    }

    public JLabel getLblEmail() {
        return lblEmail;
    }

    public void setLblEmail(JLabel lblEmail) {
        this.lblEmail = lblEmail;
    }

    public JLabel getLblNombres() {
        return lblNombres;
    }

    public void setLblNombres(JLabel lblNombres) {
        this.lblNombres = lblNombres;
    }

    public JLabel getLblTelefono() {
        return lblTelefono;
    }

    public void setLblTelefono(JLabel lblTelefono) {
        this.lblTelefono = lblTelefono;
    }

    public JRadioButton getRdAntiguo() {
        return rdAntiguo;
    }

    public void setRdAntiguo(JRadioButton rdAntiguo) {
        this.rdAntiguo = rdAntiguo;
    }

    public JRadioButton getRdEmpresa() {
        return rdEmpresa;
    }

    public void setRdEmpresa(JRadioButton rdEmpresa) {
        this.rdEmpresa = rdEmpresa;
    }

    public JRadioButton getRdNatural() {
        return rdNatural;
    }

    public void setRdNatural(JRadioButton rdNatural) {
        this.rdNatural = rdNatural;
    }

    public JRadioButton getRdNuevo() {
        return rdNuevo;
    }

    public void setRdNuevo(JRadioButton rdNuevo) {
        this.rdNuevo = rdNuevo;
    }

    public JTable getTblPaquete() {
        return tblPaquete;
    }

    public void setTblPaquete(JTable tblPaquete) {
        this.tblPaquete = tblPaquete;
    }

    public JTextField getTxtApMat() {
        return txtApMat;
    }

    public void setTxtApMat(JTextField txtApMat) {
        this.txtApMat = txtApMat;
    }

    public JTextField getTxtApPat() {
        return txtApPat;
    }

    public void setTxtApPat(JTextField txtApPat) {
        this.txtApPat = txtApPat;
    }

    public JTextField getTxtDocID() {
        return txtDocID;
    }

    public void setTxtDocID(JTextField txtDocID) {
        this.txtDocID = txtDocID;
    }

    public JTextField getTxtEmail() {
        return txtEmail;
    }

    public void setTxtEmail(JTextField txtEmail) {
        this.txtEmail = txtEmail;
    }

    public JTextField getTxtNombres() {
        return txtNombres;
    }

    public void setTxtNombres(JTextField txtNombres) {
        this.txtNombres = txtNombres;
    }

    public JTextField getTxtTelefono() {
        return txtTelefono;
    }

    public void setTxtTelefono(JTextField txtTelefono) {
        this.txtTelefono = txtTelefono;
    }

    // METODOS
    // constructor sin parametros
    public Registro() {
        initComponents();

        // inicializo estados de los radiobutton
        this.rdNatural.doClick();
        this.rdNuevo.doClick();

        // inicializo la tabla
        listaFilasTablaEnvios = new ArrayList<ObjetoTablaEnvios>();
        columnasTablaEnvios = new Vector();
        columnasTablaEnvios.add("Cantidad de Paquetes");
        columnasTablaEnvios.add("Ciudad Destino");
        modeloTablaEnvios = new DefaultTableModel(this.columnasTablaEnvios, 0) {
            public boolean isCellEditable(int row, int column) { // para que no se pueda editar directamente la tabla
                return false;
            }
        };
        this.tblPaquete.setModel(modeloTablaEnvios);
        this.tblPaquete.setCellSelectionEnabled(false); // para que no se puedan seleccionar celdas individuales
        this.tblPaquete.setRowSelectionAllowed(true);   // para que se seleccione la fila entera

        // prueba de paquetes en tabla
//        Paquete paqueteTemp = new Paquete();
//        Ciudad ciudadDestinoTemp = new Ciudad();
//        ciudadDestinoTemp.setCiudad("Caracas");
//        paqueteTemp.setCiudadByIdCiudadDestino(ciudadDestinoTemp);
//        ObjetoTablaEnvios fila = new ObjetoTablaEnvios(5, paqueteTemp);
//        listaFilasTablaEnvios.add(fila);
//        //ciudadDestinoTemp = new Ciudad();
//        //ciudadDestinoTemp.setCiudad("Brasilia");
//        Paquete paqueteTemp2 = new Paquete();
//        paqueteTemp2.setCiudadByIdCiudadDestino(new Ciudad());
//        paqueteTemp2.getCiudadByIdCiudadDestino().setCiudad("Brasilia");
//        fila = new ObjetoTablaEnvios(3, paqueteTemp2);
//        listaFilasTablaEnvios.add(fila);
//
//        for (int i = 0; i < listaFilasTablaEnvios.size(); i++) {
//            Object[] o = new Object[2];
//            o[0] = listaFilasTablaEnvios.get(i).getCantidadPaquetes();
//            o[1] = listaFilasTablaEnvios.get(i).getPaqueteModelo().getCiudadByIdCiudadDestino().getCiudad();
//            modeloTablaEnvios.addRow(o);
//        }
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        buttonGroup1 = new javax.swing.ButtonGroup();
        buttonGroup2 = new javax.swing.ButtonGroup();
        btnAceptar = new javax.swing.JButton();
        btnCancelar = new javax.swing.JButton();
        jPanel1 = new javax.swing.JPanel();
        txtDocID = new javax.swing.JTextField();
        txtEmail = new javax.swing.JTextField();
        lblEmail = new javax.swing.JLabel();
        lblTelefono = new javax.swing.JLabel();
        txtTelefono = new javax.swing.JTextField();
        lblDni = new javax.swing.JLabel();
        lblApPat = new javax.swing.JLabel();
        txtApPat = new javax.swing.JTextField();
        btnBuscar = new javax.swing.JButton();
        lblNombres = new javax.swing.JLabel();
        txtNombres = new javax.swing.JTextField();
        rdNuevo = new javax.swing.JRadioButton();
        rdAntiguo = new javax.swing.JRadioButton();
        rdNatural = new javax.swing.JRadioButton();
        rdEmpresa = new javax.swing.JRadioButton();
        lblApMat = new javax.swing.JLabel();
        txtApMat = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        jPanel3 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        tblPaquete = new javax.swing.JTable();
        btnAgregar = new javax.swing.JButton();
        btnEditar = new javax.swing.JButton();
        btnEliminar = new javax.swing.JButton();
        jLabel5 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
        setTitle("Registro de Paquetes");
        setResizable(false);
        getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        btnAceptar.setFont(new java.awt.Font("Arial", 0, 11)); // NOI18N
        btnAceptar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resources/aceptar.png"))); // NOI18N
        btnAceptar.setText("Aceptar");
        btnAceptar.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                btnAceptarMouseClicked(evt);
            }
        });
        btnAceptar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAceptarActionPerformed(evt);
            }
        });
        getContentPane().add(btnAceptar, new org.netbeans.lib.awtextra.AbsoluteConstraints(110, 560, 110, 40));

        btnCancelar.setFont(new java.awt.Font("Arial", 0, 11)); // NOI18N
        btnCancelar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resources/Cancelar.png"))); // NOI18N
        btnCancelar.setText("Cancelar");
        btnCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCancelarActionPerformed(evt);
            }
        });
        getContentPane().add(btnCancelar, new org.netbeans.lib.awtextra.AbsoluteConstraints(260, 560, -1, -1));

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "CLIENTE", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 1, 14))); // NOI18N
        jPanel1.setAutoscrolls(true);
        jPanel1.setFont(new java.awt.Font("Arial", 1, 18)); // NOI18N

        txtDocID.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                txtDocIDKeyTyped(evt);
            }
        });

        lblEmail.setFont(new java.awt.Font("Arial", 0, 11)); // NOI18N
        lblEmail.setText("E-mail: (*)");

        lblTelefono.setFont(new java.awt.Font("Arial", 0, 11)); // NOI18N
        lblTelefono.setText("Telefono: (*)");

        txtTelefono.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                txtTelefonoKeyTyped(evt);
            }
        });

        lblDni.setFont(new java.awt.Font("Arial", 0, 11)); // NOI18N
        lblDni.setText("Doc. Identidad: (*)");

        lblApPat.setFont(new java.awt.Font("Arial", 0, 11)); // NOI18N
        lblApPat.setText("Apellido Paterno: (*)");

        txtApPat.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                txtApPatKeyTyped(evt);
            }
        });

        btnBuscar.setFont(new java.awt.Font("Arial", 0, 11)); // NOI18N
        btnBuscar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resources/buscar.png"))); // NOI18N
        btnBuscar.setText("Buscar Cliente");
        btnBuscar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnBuscarActionPerformed(evt);
            }
        });

        lblNombres.setFont(new java.awt.Font("Arial", 0, 11)); // NOI18N
        lblNombres.setText("Nombres: (*)");

        txtNombres.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                txtNombresKeyTyped(evt);
            }
        });

        buttonGroup2.add(rdNuevo);
        rdNuevo.setFont(new java.awt.Font("Arial", 0, 11)); // NOI18N
        rdNuevo.setText("Nuevo Cliente");
        rdNuevo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                rdNuevoActionPerformed(evt);
            }
        });

        buttonGroup2.add(rdAntiguo);
        rdAntiguo.setFont(new java.awt.Font("Arial", 0, 11)); // NOI18N
        rdAntiguo.setText("Cliente Antiguo");
        rdAntiguo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                rdAntiguoActionPerformed(evt);
            }
        });

        buttonGroup1.add(rdNatural);
        rdNatural.setFont(new java.awt.Font("Arial", 0, 11)); // NOI18N
        rdNatural.setText("Persona Natural");
        rdNatural.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                rdNaturalActionPerformed(evt);
            }
        });

        buttonGroup1.add(rdEmpresa);
        rdEmpresa.setFont(new java.awt.Font("Arial", 0, 11)); // NOI18N
        rdEmpresa.setText("Empresa");
        rdEmpresa.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                rdEmpresaActionPerformed(evt);
            }
        });

        lblApMat.setFont(new java.awt.Font("Arial", 0, 11)); // NOI18N
        lblApMat.setText("Apellido Materno: (*)");

        txtApMat.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                txtApMatKeyTyped(evt);
            }
        });

        jLabel1.setForeground(new java.awt.Color(255, 51, 51));
        jLabel1.setText("(*) Campos Obligatorios");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(14, 14, 14)
                .addComponent(rdNuevo)
                .addGap(29, 29, 29)
                .addComponent(rdAntiguo))
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(14, 14, 14)
                .addComponent(rdNatural)
                .addGap(17, 17, 17)
                .addComponent(rdEmpresa))
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(14, 14, 14)
                .addComponent(lblDni, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(10, 10, 10)
                .addComponent(txtDocID, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(110, 110, 110)
                .addComponent(btnBuscar, javax.swing.GroupLayout.PREFERRED_SIZE, 160, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(14, 14, 14)
                .addComponent(lblNombres, javax.swing.GroupLayout.PREFERRED_SIZE, 83, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(27, 27, 27)
                .addComponent(txtNombres, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(14, 14, 14)
                .addComponent(lblApPat, javax.swing.GroupLayout.PREFERRED_SIZE, 110, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(0, 0, 0)
                .addComponent(txtApPat, javax.swing.GroupLayout.PREFERRED_SIZE, 165, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(14, 14, 14)
                .addComponent(lblApMat, javax.swing.GroupLayout.PREFERRED_SIZE, 110, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(0, 0, 0)
                .addComponent(txtApMat, javax.swing.GroupLayout.PREFERRED_SIZE, 165, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(14, 14, 14)
                .addComponent(lblEmail)
                .addGap(64, 64, 64)
                .addComponent(txtEmail, javax.swing.GroupLayout.PREFERRED_SIZE, 165, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(14, 14, 14)
                .addComponent(lblTelefono)
                .addGap(50, 50, 50)
                .addComponent(txtTelefono, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(24, 24, 24)
                .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 180, javax.swing.GroupLayout.PREFERRED_SIZE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(1, 1, 1)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(rdNuevo)
                    .addComponent(rdAntiguo))
                .addGap(7, 7, 7)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(rdNatural)
                    .addComponent(rdEmpresa))
                .addGap(7, 7, 7)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(btnBuscar)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(20, 20, 20)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(lblDni)
                            .addComponent(txtDocID, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))
                .addGap(9, 9, 9)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(lblNombres)
                    .addComponent(txtNombres, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(10, 10, 10)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(lblApPat)
                    .addComponent(txtApPat, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(10, 10, 10)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(lblApMat)
                    .addComponent(txtApMat, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(10, 10, 10)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(lblEmail)
                    .addComponent(txtEmail, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(10, 10, 10)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(lblTelefono)
                    .addComponent(txtTelefono, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(40, 40, 40)
                .addComponent(jLabel1))
        );

        getContentPane().add(jPanel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 10, 500, 310));

        jPanel3.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "ENVIO", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 1, 14))); // NOI18N
        jPanel3.setFont(new java.awt.Font("Arial", 0, 11)); // NOI18N

        tblPaquete.setFont(new java.awt.Font("Arial", 0, 11)); // NOI18N
        tblPaquete.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {

            }
        ));
        tblPaquete.setColumnSelectionAllowed(true);
        tblPaquete.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        jScrollPane1.setViewportView(tblPaquete);

        btnAgregar.setFont(new java.awt.Font("Arial", 0, 11)); // NOI18N
        btnAgregar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resources/agregar.png"))); // NOI18N
        btnAgregar.setText("Agregar");
        btnAgregar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAgregarActionPerformed(evt);
            }
        });

        btnEditar.setFont(new java.awt.Font("Arial", 0, 11)); // NOI18N
        btnEditar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resources/editar.png"))); // NOI18N
        btnEditar.setText("Editar");
        btnEditar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnEditarActionPerformed(evt);
            }
        });

        btnEliminar.setFont(new java.awt.Font("Arial", 0, 11)); // NOI18N
        btnEliminar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resources/Eliminar.png"))); // NOI18N
        btnEliminar.setText("Eliminar");
        btnEliminar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnEliminarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addGap(10, 10, 10)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel3Layout.createSequentialGroup()
                        .addComponent(btnAgregar)
                        .addGap(43, 43, 43)
                        .addComponent(btnEditar, javax.swing.GroupLayout.PREFERRED_SIZE, 113, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(46, 46, 46)
                        .addComponent(btnEliminar, javax.swing.GroupLayout.PREFERRED_SIZE, 113, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 468, javax.swing.GroupLayout.PREFERRED_SIZE)))
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(btnAgregar)
                    .addComponent(btnEditar, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnEliminar, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(11, 11, 11)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 133, javax.swing.GroupLayout.PREFERRED_SIZE))
        );

        getContentPane().add(jPanel3, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 330, 500, 220));
        getContentPane().add(jLabel5, new org.netbeans.lib.awtextra.AbsoluteConstraints(220, 540, 40, 20));

        setSize(new java.awt.Dimension(536, 659));
        setLocationRelativeTo(null);
    }// </editor-fold>//GEN-END:initComponents

    private void btnCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelarActionPerformed
        // TODO add your handling code here:
        this.dispose();
        new Menu().setVisible(true);
    }//GEN-LAST:event_btnCancelarActionPerformed

    // click a radiobutton de cliente nuevo
    private void rdNuevoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_rdNuevoActionPerformed

        this.txtApMat.setEnabled(true);
        this.txtApPat.setEnabled(true);
        this.txtDocID.setEnabled(true);
        this.txtEmail.setEnabled(true);
        this.txtNombres.setEnabled(true);
        this.txtTelefono.setEnabled(true);

        this.btnBuscar.setEnabled(false);

        this.limpiarTxt();
        this.rdNatural.setEnabled(true);
        this.rdEmpresa.setEnabled(true);

        this.cliente = null;
    }//GEN-LAST:event_rdNuevoActionPerformed

    // click a radiobuton de cliente natural
    private void rdNaturalActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_rdNaturalActionPerformed

        iniciaCampos(1);
        this.lblDni.setText("Doc. Identidad: (*)");
        this.lblNombres.setText("Nombres: (*)");
        this.lblApPat.setVisible(true);
        this.lblApMat.setVisible(true);
        this.txtApMat.setVisible(true);
        this.txtApPat.setVisible(true);

        this.lblApPat.setText("Apellido Paterno: (*)");
        this.lblApMat.setText("Apellido Materno: (*)");
        this.txtNombres.setSize(120, 20);

        this.limpiarTxt();
    }//GEN-LAST:event_rdNaturalActionPerformed

    // click a radiobuton de cliente empresa
    private void rdEmpresaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_rdEmpresaActionPerformed

        iniciaCampos(2);
        this.lblDni.setText("RUC: (*)");
        this.lblNombres.setText("Razón Social: (*)");
        this.lblApMat.setVisible(false);
        this.lblApPat.setVisible(false);
        this.txtApMat.setVisible(false);
        this.txtApPat.setVisible(false);
        
        this.txtNombres.setSize(160, 20);
        this.limpiarTxt();
    }//GEN-LAST:event_rdEmpresaActionPerformed

    //click a radiobutton de cliente antiguo
    private void rdAntiguoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_rdAntiguoActionPerformed
        this.txtApMat.setEnabled(false);
        this.txtApPat.setEnabled(false);
        this.txtDocID.setEnabled(false);
        this.txtEmail.setEnabled(false);
        this.txtNombres.setEnabled(false);
        this.txtTelefono.setEnabled(false);

        this.btnBuscar.setEnabled(true);

        this.limpiarTxt();
        this.setCliente(null);
        this.rdNatural.setEnabled(false);
        this.rdEmpresa.setEnabled(false);
    }//GEN-LAST:event_rdAntiguoActionPerformed

    // click a boton Buscar Cliente
    private void btnBuscarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnBuscarActionPerformed
        BusquedaCliente ventanaBuscarCliente = new BusquedaCliente(this);
        ventanaBuscarCliente.setVisible(true);
    }//GEN-LAST:event_btnBuscarActionPerformed

    // click en boton AgregarEnvio
    private void btnAgregarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAgregarActionPerformed
        AgregarEnvio ventanaAgregarEnvio = new AgregarEnvio(this);

        ventanaAgregarEnvio.setVisible(true);
    }//GEN-LAST:event_btnAgregarActionPerformed

    // click a boton para eliminar fila de la tabla de envios
    private void btnEliminarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEliminarActionPerformed
        
        if (this.tblPaquete.getSelectedRow() == -1){//no se selecciono niguna fila
            
            JOptionPane.showMessageDialog(null, "Debe seleccionar el Paquete a Eliminar","Error",JOptionPane.ERROR_MESSAGE);
            
        }else{
            int dialogButton = JOptionPane.YES_NO_OPTION;
            int dialogResult = JOptionPane.showConfirmDialog(null, "¿Seguro que desea eliminar este envío?", "Confirmación", dialogButton);
            if (dialogResult == JOptionPane.YES_OPTION) {
                //elimino envio

                // codigo para obtener el ObjetoTablaEnvio de la fila seleccionada
                int numFila = this.tblPaquete.getSelectedRow();
                System.out.println(this.listaFilasTablaEnvios.get(numFila).getCantidadPaquetes()
                        + " " + this.listaFilasTablaEnvios.get(numFila).getPaqueteModelo().getCiudadByIdCiudadDestino().getCiudad());
                this.listaFilasTablaEnvios.remove(numFila); //lo saco de la lista de ObjetoTabla Envio
                this.modeloTablaEnvios.removeRow(numFila); // lo saco del modelo de la tabla

            }
            if (dialogResult == JOptionPane.NO_OPTION) {
                //this.dispose();
            }
        }
    }//GEN-LAST:event_btnEliminarActionPerformed

    //click a boton para editar envio
    private void btnEditarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEditarActionPerformed
        
        if (this.tblPaquete.getSelectedRow() == -1){//no se selecciono niguna fila
            
            JOptionPane.showMessageDialog(null, "Debe seleccionar el Paquete a Editar","Error",JOptionPane.ERROR_MESSAGE);
        }else{
            // codigo para obtener el ObjetoTablaEnvio de la fila seleccionada
            numFilaEditar = this.tblPaquete.getSelectedRow();

            EditarEnvio ventanaEditarEnvio = new EditarEnvio(this, this.listaFilasTablaEnvios.get(numFilaEditar));

            ventanaEditarEnvio.setVisible(true);
        }
    }//GEN-LAST:event_btnEditarActionPerformed

    private void txtDocIDKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtDocIDKeyTyped
        char vChar = evt.getKeyChar();
        if (!(Character.isDigit(vChar)
                || (vChar == KeyEvent.VK_BACK_SPACE)
                || (vChar == KeyEvent.VK_DELETE))) {
            evt.consume();
        }
    }//GEN-LAST:event_txtDocIDKeyTyped

    private void txtNombresKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtNombresKeyTyped
        if (rdNatural.isSelected()) {
            char vChar = evt.getKeyChar();
            if (!(Character.isAlphabetic(vChar)
                    || (Character.isSpaceChar(vChar))
                    || (vChar == KeyEvent.VK_BACK_SPACE)
                    || (vChar == KeyEvent.VK_DELETE))) {
                evt.consume();
            }
        } else {
            char vChar = evt.getKeyChar();
            if (!(Character.isLetterOrDigit(vChar)
                    || (Character.isSpaceChar(vChar))
                    || (vChar == KeyEvent.VK_BACK_SPACE)
                    || (vChar == KeyEvent.VK_DELETE)
                    || (vChar == KeyEvent.VK_PERIOD))) {
                evt.consume();
            }
        }
    }//GEN-LAST:event_txtNombresKeyTyped

    private void txtApPatKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtApPatKeyTyped
        char vChar = evt.getKeyChar();
        if (!(Character.isAlphabetic(vChar)
                || (vChar == KeyEvent.VK_BACK_SPACE)
                || (vChar == KeyEvent.VK_DELETE))) {
            evt.consume();
        }
    }//GEN-LAST:event_txtApPatKeyTyped

    private void txtApMatKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtApMatKeyTyped
        char vChar = evt.getKeyChar();
        if (!(Character.isAlphabetic(vChar)
                || (vChar == KeyEvent.VK_BACK_SPACE)
                || (vChar == KeyEvent.VK_DELETE))) {
            evt.consume();
        }
    }//GEN-LAST:event_txtApMatKeyTyped

    private void txtTelefonoKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtTelefonoKeyTyped
        char vChar = evt.getKeyChar();
        if (!(Character.isDigit(vChar)
                || (vChar == KeyEvent.VK_BACK_SPACE)
                || (vChar == KeyEvent.VK_DELETE))) {
            evt.consume();
        }
    }//GEN-LAST:event_txtTelefonoKeyTyped

    private void btnAceptarMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btnAceptarMouseClicked
        int dialogButton = JOptionPane.YES_NO_OPTION;
        int dialogResult = JOptionPane.showConfirmDialog(null, "¿Desea realizar el registro?", "Confirmación", dialogButton);
        if (dialogResult == JOptionPane.YES_OPTION) {

            if (this.listaFilasTablaEnvios.isEmpty()) {  // si la lista de envios esta vacia
                JOptionPane.showMessageDialog(null, "Ingrese envíos a registrar.", "Falta de Envíos", JOptionPane.ERROR_MESSAGE);
            } else if ((this.rdNatural.isSelected() && (this.txtEmail.getText().trim().isEmpty() || this.txtApMat.getText().trim().isEmpty()
                    || this.txtApPat.getText().trim().isEmpty() || this.txtDocID.getText().trim().isEmpty()
                    || this.txtNombres.getText().trim().isEmpty() || this.txtTelefono.getText().trim().isEmpty()))
                    || (this.rdEmpresa.isSelected() && (this.txtEmail.getText().trim().isEmpty() || this.txtDocID.getText().trim().isEmpty()
                    || this.txtNombres.getText().trim().isEmpty() || this.txtTelefono.getText().trim().isEmpty()))
                    || (this.rdAntiguo.isSelected() && (this.cliente == null))) { // si no se ha ingresado algun dato obligatorio
                JOptionPane.showMessageDialog(null, "Ingrese todos los datos obligatorios.", "Datos Incompletos", JOptionPane.ERROR_MESSAGE);
            } else {

                EstadoRegistro ventanaEspera = new EstadoRegistro();
                new WorkerRegistro(this, ventanaEspera).execute();
                //this.setFocusableWindowState(false);
                this.dispose();
                ventanaEspera.setVisible(true);
            }
        }

        if (dialogResult == JOptionPane.NO_OPTION) {
            //this.dispose();
        }
    }//GEN-LAST:event_btnAceptarMouseClicked

    private void btnAceptarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAceptarActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_btnAceptarActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Registro.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Registro.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Registro.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Registro.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Registro().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnAceptar;
    private javax.swing.JButton btnAgregar;
    private javax.swing.JButton btnBuscar;
    private javax.swing.JButton btnCancelar;
    private javax.swing.JButton btnEditar;
    private javax.swing.JButton btnEliminar;
    private javax.swing.ButtonGroup buttonGroup1;
    private javax.swing.ButtonGroup buttonGroup2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JLabel lblApMat;
    private javax.swing.JLabel lblApPat;
    private javax.swing.JLabel lblDni;
    private javax.swing.JLabel lblEmail;
    private javax.swing.JLabel lblNombres;
    private javax.swing.JLabel lblTelefono;
    private javax.swing.JRadioButton rdAntiguo;
    public javax.swing.JRadioButton rdEmpresa;
    public javax.swing.JRadioButton rdNatural;
    private javax.swing.JRadioButton rdNuevo;
    private javax.swing.JTable tblPaquete;
    private javax.swing.JTextField txtApMat;
    private javax.swing.JTextField txtApPat;
    private javax.swing.JTextField txtDocID;
    private javax.swing.JTextField txtEmail;
    private javax.swing.JTextField txtNombres;
    private javax.swing.JTextField txtTelefono;
    // End of variables declaration//GEN-END:variables

    // metodo para limpiar los textbox de clientes
    private void limpiarTxt() {
        this.txtNombres.setText("");
        this.txtApMat.setText("");
        this.txtApPat.setText("");
        this.txtDocID.setText("");
        this.txtEmail.setText("");
        this.txtTelefono.setText("");
        this.setCliente(null);
    }

    // metodo para guardar el envio obtenido de la ventan RegistroEnvio
    public void agregarEnvio(ObjetoTablaEnvios envio) {
        this.listaFilasTablaEnvios.add(envio);
        int numFilas = modeloTablaEnvios.getRowCount();
        Object[] o = new Object[2];
        o[0] = listaFilasTablaEnvios.get(numFilas).getCantidadPaquetes();
        o[1] = listaFilasTablaEnvios.get(numFilas).getPaqueteModelo().getCiudadByIdCiudadDestino().getCiudad();
        modeloTablaEnvios.addRow(o);
    }

    // metodo para guardar el envio editado
    public void editarEnvio(ObjetoTablaEnvios envio) {
        // actualizo lista de ObjetoTablaEnvios
        listaFilasTablaEnvios.remove(numFilaEditar);
        listaFilasTablaEnvios.add(numFilaEditar, envio);

        // vuelvo a rellenar la tabla
        modeloTablaEnvios.removeRow(numFilaEditar);
        Object[] o = new Object[2];
        o[0] = listaFilasTablaEnvios.get(numFilaEditar).getCantidadPaquetes();
        o[1] = listaFilasTablaEnvios.get(numFilaEditar).getPaqueteModelo().getCiudadByIdCiudadDestino().getCiudad();
        modeloTablaEnvios.addRow(o);
    }

    // metodo para guardar el cliente antiguo que se busco
    public void agregarCliente(Cliente cliente, boolean esPersona) {
//        this.cliente=cliente;
//        if (selected){  // si es cliente persona natural
//            this.rdNatural.setSelected(true);
//            this.limpiarTxt();
//            this.txtApMat.setText(this.cliente.getApMaterno());
//            this.txtApPat.setText(this.cliente.getApPaterno());
//            this.txtDocID.setText(this.cliente.getDni());
//            this.txtEmail.setText(this.cliente.getEmail());
//            this.txtNombres.setText(this.cliente.getNombres());
//            this.txtTelefono.setText(this.cliente.getTelefono());
//        }else{  // si es cliente empresa
//            this.rdEmpresa.setSelected(true);
//            this.limpiarTxt();
//            this.txtNombres.setText(this.cliente.getRazonSocial());
//            this.txtDocID.setText(this.cliente.getRuc());
//            this.txtEmail.setText(this.cliente.getEmail());
//        }

        this.rdAntiguo.doClick();
        if (esPersona) {
            this.rdNatural.doClick();
            txtNombres.setText(cliente.getNombres());
            txtApPat.setText(cliente.getApPaterno());
            txtApMat.setText(cliente.getApMaterno());
            txtDocID.setText(cliente.getDni());
        } else {
            this.rdEmpresa.setEnabled(true);
            this.rdEmpresa.doClick();
            this.rdEmpresa.setEnabled(false);
            txtNombres.setText(cliente.getRazonSocial());
            txtDocID.setText(cliente.getRuc());
        }
        txtEmail.setText(cliente.getEmail());
        txtTelefono.setText(cliente.getTelefono());
        this.cliente = cliente;
    }

    public boolean validaCorreo(String email) {
        boolean result = true;
        try {
            InternetAddress emailAddr = new InternetAddress(email);
        } catch (AddressException ex) {
            return false;
        }
        return result;
    }

    private void iniciaCampos(int i) {
        if (i == 2) {
            MaxLengthTextDocument maxID = new MaxLengthTextDocument();
            MaxLengthTextDocument maxNom = new MaxLengthTextDocument();

            maxNom.setMaxChars(30);
            maxID.setMaxChars(11);

            txtNombres.setDocument(maxNom);
            txtDocID.setDocument(maxID);

        } else if (i == 1) {
            MaxLengthTextDocument maxApPat = new MaxLengthTextDocument();
            MaxLengthTextDocument maxApMat = new MaxLengthTextDocument();
            MaxLengthTextDocument maxNom = new MaxLengthTextDocument();
            MaxLengthTextDocument maxTel = new MaxLengthTextDocument();
            MaxLengthTextDocument maxID = new MaxLengthTextDocument();
            MaxLengthTextDocument maxEmail = new MaxLengthTextDocument();

            maxNom.setMaxChars(15);
            maxID.setMaxChars(9);
            maxApPat.setMaxChars(20);
            maxApMat.setMaxChars(20);
            maxTel.setMaxChars(10);
            maxEmail.setMaxChars(30);

            txtNombres.setDocument(maxNom);
            txtApPat.setDocument(maxApPat);
            txtApMat.setDocument(maxApMat);
            txtDocID.setDocument(maxID);
            txtTelefono.setDocument(maxTel);
            txtEmail.setDocument(maxEmail);
        }
    }
}
